<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>throttle 演示</title>
    <style>
        #div1 {
            border: 1px solid #ccc;
            width: 200px;
            height: 200px;
        }
    </style>
</head>

<body>
    <div id="div1" draggable="true">可拖拽</div>
    <script>
        const div1 = document.getElementById('div1');

        // let timer = null;
        // div1.addEventListener('drag', function (e) {
        //     if (timer) {
        //         return
        //     }
        //     // 会发生频繁操作，只要拖拽一点点就会触发这个log事件
        //     timer = setTimeout(() => {
        //         console.log(e.offsetX, e.offsetY);

        //         timer = null;
        //     }, 100);
        // })

        function throttle(fn, delay = 100) {
            let timer = null;
            return function () {
                if (timer) {
                    return;
                }
                timer = setTimeout(() => {
                    fn.apply(this, arguments);
                    timer = null;
                }, delay);
            }
        }

        div1.addEventListener('drag', throttle(function (e) {
            console.log(e.offsetX, e.offsetY);
        }))
    </script>
</body>

</html>